<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import CustomTabBar from "@/components/CustomTabBar.vue";
import { getHrJobListApi } from "@/api/position";

// 当前选中的tab索引
const currentTab = ref(0);

// tabs数据
const tabs = ref([
  { id: 1, name: "招聘中", value: 1 },
  { id: 2, name: "已关闭", value: 2 },
  { id: 3, name: "违规删除", value: 3 },
]);

// 职位列表数据
const positionList = ref([]);
const loading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const totalPages = ref(0);
const totals = ref(0);
const scrollViewHeight = ref(500); // 添加scroll-view高度

// 获取职位列表
const getPositionList = async (isRefresh = false) => {
  console.log(
    "获取职位列表 - isRefresh:",
    isRefresh,
    "currentPage:",
    currentPage.value
  );

  if (loading.value && !isRefresh) {
    console.log("正在加载中，跳过");
    return;
  }
  if (loadingMore.value && isRefresh) {
    console.log("正在加载更多，跳过刷新");
    return;
  }

  try {
    if (isRefresh) {
      currentPage.value = 1;
      loading.value = true;
      positionList.value = []; // 清空列表
      console.log("刷新模式 - 清空列表，重置页码");
    } else {
      if (!hasMore.value) {
        console.log("无更多数据可加载");
        return;
      }
      loadingMore.value = true;
      console.log("加载更多模式 - 页码:", currentPage.value);
    }

    const currentTabData = tabs.value[currentTab.value];
    const params = {
      pageNo: isRefresh ? 1 : currentPage.value,
      pageSize: pageSize.value,
      status: currentTabData.value, // 全部传null，其他传对应值
    };

    console.log("请求参数:", params);
    const response = await getHrJobListApi(params);
    console.log("职位列表响应:", response);

    if (response) {
      totalPages.value = response.totalPages || 0;
      totals.value = response.totals || 0;

      console.log(
        "响应数据 - totalPages:",
        totalPages.value,
        "totals:",
        totals.value,
        "list.length:",
        (response.list || []).length
      );

      if (isRefresh) {
        positionList.value = response.list || [];
        currentPage.value = 1;
        console.log("刷新完成 - 当前列表长度:", positionList.value.length);
      } else {
        positionList.value.push(...(response.list || []));
        console.log("加载更多完成 - 当前列表长度:", positionList.value.length);
      }

      // 判断是否还有更多数据
      hasMore.value = currentPage.value < totalPages.value;
      console.log(
        "分页状态 - hasMore:",
        hasMore.value,
        "currentPage:",
        currentPage.value,
        "totalPages:",
        totalPages.value
      );
    } else {
      console.error("响应数据为空");
    }
  } catch (error) {
    console.error("获取职位列表失败:", error);
    uni.showToast({
      title: "获取职位列表失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    loadingMore.value = false;
    console.log(
      "请求结束 - loading:",
      loading.value,
      "loadingMore:",
      loadingMore.value
    );
  }
};

// 切换tab
const switchTab = (index) => {
  if (currentTab.value === index) return;
  currentTab.value = index;
  console.log("切换到tab:", tabs.value[index].name);

  // 重置分页状态
  currentPage.value = 1;
  positionList.value = [];
  hasMore.value = true;
  loading.value = false;
  loadingMore.value = false;

  // 重新加载数据
  getPositionList(true);
};

// 上拉加载更多
const onLoadMore = () => {
  console.log(
    "上拉加载更多 - currentPage:",
    currentPage.value,
    "totalPages:",
    totalPages.value
  );

  if (loadingMore.value || !hasMore.value) {
    console.log("已在加载中或无更多数据");
    return;
  }

  const nextPage = currentPage.value + 1;
  if (nextPage > totalPages.value) {
    console.log("已达最后一页");
    hasMore.value = false;
    return;
  }

  currentPage.value = nextPage;
  getPositionList(false);
};

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log("滚动到底部 - 触发加载更多");
  onLoadMore();
};

// 计算scroll-view高度
const calculateScrollHeight = () => {
  const systemInfo = uni.getSystemInfoSync();
  console.log("系统信息:", systemInfo);

  // 计算可用高度：屏幕高度 - 状态栏 - header - tabs - tabbar - 安全区域
  let availableHeight = systemInfo.windowHeight;

  // uni.upx2px() 转换rpx到px
  const headerHeight = uni.upx2px(88 + 40); // header + padding
  const tabsHeight = uni.upx2px(70); // tabs高度
  const tabbarHeight = uni.upx2px(98); // tabbar高度

  availableHeight = availableHeight - headerHeight - tabsHeight - tabbarHeight;

  // 添加安全区域底部高度
  const safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0;
  availableHeight -= safeAreaBottom;

  scrollViewHeight.value = Math.max(availableHeight, 300); // 最小高度300px
  console.log(
    "计算的scroll-view高度:",
    scrollViewHeight.value,
    "原始窗口高度:",
    systemInfo.windowHeight
  );
};

// 格式化薪资显示
const formatSalary = (job) => {
  if (job.beginSalary && job.endSalary && job.monthlySalary) {
    return `${job.beginSalary}-${job.endSalary}K·${job.monthlySalary}个月`;
  }
  return "面议";
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: "招聘中",
    2: "已关闭",
    3: "违规删除",
  };
  return statusMap[status] || "未知状态";
};

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 1:
      return "#00bdb4"; // 招聘中 - 绿色
    case 2:
      return "#999999"; // 已关闭 - 灰色
    case 3:
      return "#ff4d4f"; // 违规删除 - 红色
    default:
      return "#999999";
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 右上角按钮点击事件 - 跳转到发布职位页面
const handleRightIconClick = () => {
  console.log("跳转到发布职位页面");
  uni.navigateTo({
    url: "/pages/company/position/addPosition",
  });
};

// 点击职位项 - 跳转到职位编辑页面
const handlePositionClick = (position) => {
  console.log("点击职位:", position);
  // 跳转到职位编辑页面，携带jobId
  uni.navigateTo({
    url: `/pages/company/position/addPosition?jobId=${position.id}`,
  });
};

// 页面加载时获取数据
onMounted(() => {
  console.log("职位页面加载 - 初始化数据");

  // 计算scroll-view高度
  calculateScrollHeight();

  // 重置状态
  currentPage.value = 1;
  positionList.value = [];
  hasMore.value = true;

  // 监听刷新事件
  uni.$on("refreshJobList", () => {
    console.log("收到职位列表刷新事件");
    refreshData();
  });

  // 获取数据
  getPositionList(true);
});

// 页面显示时刷新数据
function onShow() {
  console.log("职位列表页面显示 - 检查是否需要刷新");
  // 可以在这里添加其他需要在页面显示时执行的逻辑
}

// 刷新数据方法
const refreshData = () => {
  console.log("刷新职位列表数据");
  currentPage.value = 1;
  positionList.value = [];
  hasMore.value = true;
  getPositionList(true);
};

// 页面卸载时清理
onUnmounted(() => {
  // 移除事件监听
  uni.$off("refreshJobList");
});
</script>

<template>
  <view class="position-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="header-left"></view>
        <text class="header-title">我发布的职位</text>
        <view class="header-right" @click="handleRightIconClick">
          <image
            class="right-icon"
            src="/static/icons/company/submit.png"
          ></image>
        </view>
      </view>
    </view>

    <!-- Tabs导航 -->
    <view class="tabs-container">
      <scroll-view class="tabs-scroll" scroll-x>
        <view class="tabs">
          <view
            class="tab-item"
            :class="{ active: currentTab === index }"
            v-for="(tab, index) in tabs"
            :key="tab.id"
            @click="switchTab(index)"
          >
            <text class="tab-text">{{ tab.name }}</text>
            <view class="tab-line" v-if="currentTab === index"></view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <scroll-view
        class="content-scroll"
        scroll-y
        @scrolltolower="onScrollToLower"
        lower-threshold="50"
        :style="{ height: scrollViewHeight + 'px' }"
      >
        <!-- 加载中提示 -->
        <view
          v-if="loading && positionList.length === 0"
          class="loading-wrapper"
        >
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 职位列表 -->
        <view class="position-list" v-else-if="positionList.length > 0">
          <view
            class="position-item"
            v-for="position in positionList"
            :key="position.id"
            @click="handlePositionClick(position)"
          >
            <view class="position-header">
              <view class="position-title">
                <text class="position-name">{{ position.jobName }}</text>
                <view
                  class="position-status"
                  :style="{ color: getStatusColor(position.status) }"
                >
                  <text class="status-text">{{
                    getStatusText(position.status)
                  }}</text>
                </view>
              </view>
              <view class="position-salary">
                <text class="salary-text">{{ formatSalary(position) }}</text>
              </view>
            </view>

            <view class="position-info">
              <view class="info-item">
                <text class="info-text">经验要求：{{ position.expYears }}</text>
              </view>
              <view class="info-item">
                <text class="info-text">学历要求：{{ position.edu }}</text>
              </view>
              <view class="info-item">
                <text class="info-text">工作地点：{{ position.city }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-else-if="!loading">
          <text class="empty-text">暂无职位数据</text>
        </view>

        <!-- 加载更多 -->
        <view v-if="loadingMore" class="load-more">
          <text class="load-text">加载中...</text>
        </view>

        <!-- 已到底部 -->
        <view v-else-if="!hasMore && positionList.length > 0" class="no-more">
          <text class="no-more-text">已经到底了</text>
        </view>
      </scroll-view>
    </view>

    <!-- 底部导航 -->
    <CustomTabBar :currentIndex="1" />
  </view>
</template>

<style scoped lang="less">
.position-container {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 98rpx; /* 给底部tabbar留出空间 */
}

/* 页头样式 */
.header {
  background-color: #00bdb4;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  padding-top: calc(20rpx + var(--status-bar-height, 0));
}

.header-left {
  width: 60rpx;
  height: 60rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.header-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-icon {
  width: 48rpx;
  height: 48rpx;
}

/* Tabs样式 */
.tabs-container {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.tabs-scroll {
  white-space: nowrap;
}

.tabs {
  display: flex;
  justify-content: flex-start;
  padding: 0 30rpx;
}

.tab-item {
  position: relative;
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.tab-text {
  font-size: 26rpx;
  color: #666666;
  transition: color 0.3s;
  white-space: nowrap;
}

.tab-item.active .tab-text {
  color: #00bdb4;
  font-weight: 600;
}

.tab-line {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #00bdb4;
  border-radius: 2rpx;
}

/* 内容区域样式 */
.content {
  flex: 1;
  background-color: #f8f8f8;
  overflow: hidden;
  position: relative;
}

.content-scroll {
  width: 100%;
  box-sizing: border-box;
  position: relative;
}

.position-list {
  padding: 20rpx;
}

.position-item {
  background-color: #ffffff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    background-color: #f8f8f8;
  }
}

.position-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.position-title {
  flex: 1;
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.position-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  margin-right: 20rpx;
}

.position-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background-color: rgba(0, 189, 180, 0.1);
}

.status-text {
  font-size: 24rpx;
  font-weight: 500;
}

.position-salary {
  text-align: right;
}

.salary-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #ff6b35;
}

.position-info {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-text {
  font-size: 28rpx;
  color: #666666;
}

/* 状态样式 */
.loading-wrapper,
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #999999;
}

.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.load-text {
  font-size: 28rpx;
  color: #999999;
}

.no-more-text {
  font-size: 28rpx;
  color: #cccccc;
}
</style>